package cn.senjoeson.triper.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.senjoeson.mylibrary.utilschanged.LogUtils;
import cn.senjoeson.triper.R;
import cn.senjoeson.triper.base.GreenDaoManager;
import cn.senjoeson.triper.bean.PlaceBean;
import cn.senjoeson.triper.bean.Plan;
import cn.senjoeson.triper.dao.PlaceBeanDao;
import cn.senjoeson.triper.dao.PlanDao;
import cn.senjoeson.triper.wrapper.SimpleTextChangeListener;

/**
 * @author Android
 * @date 2018/1/3
 */

public class TripRVAdapter extends RecyclerView.Adapter {

    private List<Plan> mDatas;
    public SimpleTextChangeListener mWatcher;
    private PlanDao mPlanDao;
    private OnItemClickListener mOnItemClickListener;

    public void setDatas(List<Plan> list) {
        this.mDatas = list;
        mPlanDao = GreenDaoManager.getInstance().getNewSession().getPlanDao();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder1, int position) {
        final ViewHolder mHolder = (ViewHolder) holder1;
        final Plan mPlan = mDatas.get(position);
        int days = mPlan.getDays();
        Spanned spanned = Html.fromHtml("<big><big>" + days + "</big></big>Days");
        mHolder.mDays.setText(spanned);
        mHolder.mSetDate.setText(mPlan.getStartDate() + "---" + mPlan.getEndDate());

        if (mPlan.getTripName() != null) {
            mHolder.mTripName.setText("" + mPlan.getTripName());
        }
        mHolder.mListItemMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHolder.mMoreSelect.setVisibility(View.VISIBLE);
                getFocus(mHolder.mTripName, false, mPlan);
            }
        });
        mHolder.mMoreSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHolder.mMoreSelect.setVisibility(View.GONE);
                getFocus(mHolder.mTripName, false, mPlan);
            }
        });
        mHolder.mDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.d("下载");
                getFocus(mHolder.mTripName, false, mPlan);
                mHolder.mMoreSelect.setVisibility(View.GONE);
            }
        });
        mHolder.mDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.d("删除");
                deleteItem(mPlan);
                notifyDataSetChanged();
                getFocus(mHolder.mTripName, false, mPlan);
                mHolder.mMoreSelect.setVisibility(View.GONE);
            }
        });
        mHolder.mTripName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFocus(mHolder.mTripName, true, mPlan);

            }
        });
        mHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(v, mHolder.getAdapterPosition(), mPlan);
                }
            }
        });
        mHolder.mTripName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    //这里添加处理动作
                    mHolder.mTripName.clearFocus();
                    return true;
                }
                return false;
            }


        });
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        if (onItemClickListener != null) {
            this.mOnItemClickListener = onItemClickListener;

        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position, Plan plan);
    }

    private void getFocus(EditText editText, boolean flag, final Plan mPlan) {
        editText.setFocusableInTouchMode(flag);
        editText.setFocusable(flag);
        if (flag) {
            editText.requestFocus();
            final String tempText = editText.getText().toString().trim();
            mWatcher = new SimpleTextChangeListener() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    super.onTextChanged(s, start, before, count);
                    if (TextUtils.equals(s.toString(), tempText)) {
                        return;
                    } else {
                        mPlan.setTripName(s.toString());
                        mPlanDao.update(mPlan);
                    }

                }
            };
            editText.addTextChangedListener(mWatcher);
            LogUtils.d("获取焦点");
        } else {
            if (null != mWatcher) {
                editText.removeTextChangedListener(mWatcher);
            }
            editText.clearFocus();
            LogUtils.d("失去焦点");
        }
    }


    public void addItem(Plan e) {
        mDatas.add(e);
        notifyDataSetChanged();
    }

    public void deleteItem(Plan e) {
        if (mDatas.contains(e)) {
            mDatas.remove(e);
            mPlanDao.delete(e);
            PlaceBeanDao placeBeanDao = GreenDaoManager.getInstance().getNewSession().getPlaceBeanDao();
            List<PlaceBean> list = placeBeanDao.queryBuilder().where(PlaceBeanDao.Properties.Planid.eq(e.getPlanId())).build().list();
            placeBeanDao.deleteInTx(list);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getItemCount() {
        return mDatas == null ? 0 : mDatas.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv)
        ImageView mIv;
        @BindView(R.id.tripName)
        EditText mTripName;
        @BindView(R.id.setDate)
        TextView mSetDate;
        @BindView(R.id.lineaarlayout)
        LinearLayout mLineaarlayout;
        @BindView(R.id.list_item_more)
        ImageView mListItemMore;
        @BindView(R.id.days)
        TextView mDays;
        @BindView(R.id.download)
        ImageView mDownload;
        @BindView(R.id.delete)
        ImageView mDelete;
        @BindView(R.id.more_select)
        RelativeLayout mMoreSelect;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
